package com.gexiaobao.pigeon.ui.fragment.mine.banking.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentAccountTransferBinding
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.ui.view.MyTextWatcher
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @author     xwhuj
 * @date       2025/2/14 9:05
 * @Describe   转账
 */
class ActivityAccountTransfer : BaseActivity<MineBankingViewModel, FragmentAccountTransferBinding>() {

    private var mOrderDetailId = 0
    private var mOrderId: Int = 0
    private var payDialog: RxPayDialog? = null
    private var isResendCode: Boolean = false

    private var mToUserName = ""
    private var mToUserPhone = ""

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.includeBar.toolbar.initClose("转账") {
            finish()
        }
        val mOrgId = intent.getIntExtra("orgId", 0)
        val userId = intent.getIntExtra("userId", 0)
        showLoading(getString(R.string.loading))
        mViewModel.getTransQrInfo(userId, mOrgId)
        mDatabind.etInvestMoney.addTextChangedListener(MyTextWatcher(2, mDatabind.etInvestMoney))
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.investMoneyCommit) {
            when (it.id) {
                R.id.invest_money_commit -> {
                    isResendCode = false
                    applyTransfer()
                }
            }
        }
    }

    private fun applyTransfer() {
        var payFor = 0
        if (mViewModel.transferMoney.get().isNotEmpty()) {
            payFor = (mViewModel.transferMoney.get().toDouble() * 100).toInt()
        }
        when {
            mViewModel.payeeName.get().isEmpty() -> showMessage("收款人姓名不能为空")
            mViewModel.payeePhone.get().isEmpty() -> showMessage("收款人电话不能为空")
            !Util.isTelPhoneNumber(mViewModel.payeePhone.get()) -> showMessage(resources.getString(R.string.user_phone_number_wrong))
            payFor <= 0 -> showMessage("金额不能为空")
            else -> requestOrgMemberTransfer(payFor)
        }
    }

    private fun requestOrgMemberTransfer(payFor: Int) {
        val map = mapOf("toUserName" to mToUserName, "toUserPhone" to mToUserPhone, "money" to payFor)
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        showLoading(getString(R.string.loading))
        mViewModel.orgMemberTransfer(body)
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        /** 会员转账-web组织 */
        mViewModel.orgMemberTransferResult.observe(this) {
            dismissLoading()
            mOrderId = it.orderId
            if (!isResendCode) {
                showPayDialog()
            }
        }
        /** 获取转账信息 */
        mViewModel.getTransQrInfoResult.observe(this) {
            mToUserName = it.toUserName
            mToUserPhone = it.toUserPhone
            mViewModel.availableBalances.set(SettingUtil.div(it.money.toDouble(), 100.00, 2).toString())
            mViewModel.payeeName.set(it.showPayeeName)
            mViewModel.payeePhone.set(mToUserPhone)
        }
        /** 确认支付 */
        mViewModel.payResult.observe(this) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                mOrderDetailId = it.orderId
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                workWithResponseData()
            }, {
                payDialog?.dismiss()
                RxToast.error(it.msg)
            })
        }
    }

    @SuppressLint("SetTextI18n")
    private fun workWithResponseData() {
        payDialog?.showBottomView()
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent("转账成功")
        payDialog?.setSureBtnContent("关闭")
        payDialog?.setCancelBtnContent("订单详情")
    }

    private fun onBackToMineBankPage() {
        startActivity<ActivityAccountOrderDetail>("orderId" to mOrderDetailId)
        finish()
    }

    var payPassDialog: PayPassDialog? = null
    private fun showPayDialog() {
        payPassDialog = PayPassDialog(this)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                isResendCode = true
                requestOrgMemberTransfer((mViewModel.transferMoney.get().toDouble() * 100).toInt())
            }

            override fun onPassFinish(verifyCode: String?) {
//                payPassDialog?.dismiss()
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(mOrderId, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)

            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(this)
        payDialog!!.loadingDialog()
        payDialog!!.setSureListener {
            payDialog!!.dismiss()
            finish()
        }
        payDialog!!.setCancelListener {
            payDialog!!.dismiss()
            onBackToMineBankPage()
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

}